from ninja import Router

from apps.commom.good import GoodSimpleSerializer, GoodSerializer
from apps.schemas import R
from models.models import Goods, BrowsingRecord
from utils.auth import AgentAuthBearer
from utils.decorators import handle_exception

agent_good_router = Router(tags=["前端商品"], auth=AgentAuthBearer())


@agent_good_router.get("/goods", summary="获取商品")
@handle_exception("没有找到相关商品")
def get_goods(request):
    goods = Goods.objects.filter(type__name="水卡套餐", status=1)
    return R.ok(data=GoodSimpleSerializer(goods, many=True).data)


@agent_good_router.get("/goods/{good_id}", summary="获取商品详情")
@handle_exception("没有找到相关商品")
def get_good(request, good_id):
    good = Goods.objects.get(id=good_id)
    good.browsing_number += 1
    good.save()
    # todo 添加浏览浏览记录
    if BrowsingRecord.objects.filter(user=request.user, good=good).aexists():
        for item in BrowsingRecord.objects.filter(user=request.user, good=good):
            item.save()
    else:
        BrowsingRecord.objects.create(user=request.user, good=good)
    return R.ok(data=GoodSerializer(good).data)